import NetService from './net.service'
import { ref } from 'vue'
import { Service, injectable, mutex } from './service'
import { StructuresMap } from '@/pages/design/service/item/read.type'

@injectable
export default class StructuresService extends Service {
  public structures = ref([] as StructuresMap[])
  private netService = new NetService()

  @mutex
  async load () {
    // 加载全部 区段 数据
    // 判断是否全部加载 如果已经加载 忽略
    const res = await this.netService.get('/structures/list')

    if (res?.success) {
      res?.data.forEach((item: { type: string | number; id: number | string }, index: number) => {
        item.id = item.id.toString(16).replace('"', '').replace('"', '').toUpperCase()
      })
      this.structures.value = res?.data
    }
  }

  async add (params: {
    id: string;
    startPosition: number;
    endPosition: number;
    type:number;
    width:number
  }) {
    const res = await this.netService.post('/structures/insert', params)
    if (res?.success) {
      params.id = parseInt(params.id).toString(16).toUpperCase()
      params.endPosition = Number(params.endPosition)
      params.startPosition = Number(params.startPosition)
      params.width = Number(params.width)
      this.structures.value.push(params)
    }
    return res
  }

  async change (params: {
    id: string;
    startPosition: number;
    endPosition: number;
    type:number;
    width:number
  }) {
    const res = await this.netService.post('/structures/update', params)
    if (res?.success) {
      params.id = parseInt(params.id).toString(16).toUpperCase()
      params.endPosition = Number(params.endPosition)
      params.startPosition = Number(params.startPosition)
      params.width = Number(params.width)

      const delIndex = this.structures.value.findIndex((e, index) => {
        return e.id === params.id
      })
      this.structures.value.splice(delIndex, 1, params)
    }
    return res
  }

  async del (params: { id: string }) {
    const res = await this.netService.post('/structures/delete', params, 'posturl')
    if (res?.success) {
      const delIndex = this.structures.value.findIndex((e, index) => {
        return e.id === parseInt(params.id).toString(16).toUpperCase()
      })
      this.structures.value.splice(delIndex, 1)
    }
    return res
  }
}
